package cn.stylefeng.guns.modular.agv.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;

import cn.stylefeng.guns.modular.agv.entity.HikAgvRoadWay;
import cn.stylefeng.guns.modular.agv.entity.HikAgvRoadWayJL;
import cn.stylefeng.guns.modular.agv.entity.HikAgvTask;
import cn.stylefeng.guns.modular.agv.entity.HikAgvTaskJL;
import cn.stylefeng.guns.modular.agv.mapper.HikAgvRoadWayJLMapper;
import cn.stylefeng.guns.modular.agv.mapper.HikAgvRoadWayMapper;
import cn.stylefeng.guns.modular.agv.mapper.HikAgvTaskJLMapper;
import cn.stylefeng.guns.modular.agv.model.params.HiKAgvCallbackParm;
import cn.stylefeng.guns.modular.agv.model.params.HikAgvTaskJLParam;

import cn.stylefeng.guns.modular.agv.model.params.HikAgvTaskParam;
import cn.stylefeng.guns.modular.agv.model.result.HikAgvTaskJLResult;

import cn.stylefeng.guns.modular.agv.service.HikAgvTaskJLService;
import cn.stylefeng.guns.modular.agv.util.HikApiUtils;
import cn.stylefeng.guns.modular.agv.util.HikRsVo;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.service.BasicCustomerService;
import cn.stylefeng.guns.modular.hx.order.entity.HxOrderPutDetailed;
import cn.stylefeng.guns.modular.rest.aop.UserAop;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 吉林海康AGV任务单 服务实现类
 * </p>
 *
 * @author lww
 * @since 2024-10-23
 */
@Service
public class HikAgvTaskJLServiceImpl extends ServiceImpl<HikAgvTaskJLMapper, HikAgvTaskJL> implements HikAgvTaskJLService {
    @Autowired
    private HikAgvRoadWayJLMapper  hikAgvRoadWayJLMapper;

    @Autowired
    private UserAop userAop;

    @Autowired
    private BasicCustomerService basicCustomerService;
    @Override
    public void add(HikAgvTaskJLParam param){
        HikAgvTaskJL entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(HikAgvTaskJLParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(HikAgvTaskJLParam param){
        HikAgvTaskJL oldEntity = getOldEntity(param);
        HikAgvTaskJL newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public HikAgvTaskJLResult findBySpec(HikAgvTaskJLParam param){
        return null;
    }

    @Override
    public List<HikAgvTaskJLResult> findListBySpec(HikAgvTaskJLParam param){
        return this.baseMapper.customList(param);
    }

    @Override
    public LayuiPageInfo findPageBySpec(HikAgvTaskJLParam param, String condition){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param,condition);
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(HikAgvTaskJLParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private HikAgvTaskJL getOldEntity(HikAgvTaskJLParam param) {
        return this.getById(getKey(param));
    }

    private HikAgvTaskJL getEntity(HikAgvTaskJLParam param) {
        HikAgvTaskJL entity = new HikAgvTaskJL();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }
    //长春下达agv任务
    @Override
    public ResponseData addTaskcc(HikAgvTaskJLParam param) {

        BasicCustomer r = basicCustomerService.lambdaQuery().eq(BasicCustomer::getDeptId, param.getDeptId()).one();


// 查询当前终点 是否有同起点且未离开的任务
        HikAgvTaskJLParam q = new HikAgvTaskJLParam();
        q.setStat("01");
        q.setSrcPositionCode(param.getSrcPositionCode());
        List<HikAgvTaskJLResult> taskList = this.baseMapper.get01TaskList(q);
        if(taskList!=null && taskList.size() > 0){
            return ResponseData.error("起点【"+param.getSrcPositionCode()+"】存在未执行的任务，无法再次创建！！！");
        }
        HikAgvRoadWayJL hikAgvRoadWayJL = new HikAgvRoadWayJL();
        hikAgvRoadWayJL.setRoadWayCode(param.getTarPositionCode());

        String roadWayCode = StringUtils.leftPad(param.getTarPositionCode(),3,"0");
        HikRsVo hikRsVo = HikApiUtils.genAgvSchedulingTaskJL(r.getAgvBaseUrl(), param);
        if (hikRsVo == null) {
            return ResponseData.error("接口调用错误");
        } else if (!"0".equals(hikRsVo.getCode() )) {
            return ResponseData.error(hikRsVo.getMessage());
        } else {
            //更新巷道信息
            //查询当前通道剩余托数
            Integer fullNum = hikAgvRoadWayJLMapper.getFullNum(param.getTarPositionCode());
            if(fullNum != null && fullNum < 1){
                param.setOverFlag("red");
            }
            param.setTaskNo(hikRsVo.getData());
            HikAgvTaskJL entity = getEntity(param);
            this.save(entity);
            //更新巷道信息

        }
        return ResponseData.success();
    }
    @Override
    public ResponseData clear(String roadWayCode) {
        User user = userAop.getUser();
        BasicCustomer r = basicCustomerService.lambdaQuery().eq(BasicCustomer::getDeptId, user.getDeptId()).one();

        HikRsVo hikRsVo = HikApiUtils.clearRoadWay(r.getAgvBaseUrl(), roadWayCode);
        if (hikRsVo == null) {
            return ResponseData.error("接口调用错误");
        } else if (!"0".equals(hikRsVo.getCode() )) {
            return ResponseData.error(hikRsVo.getMessage());
        }
        HikAgvRoadWayJL hikAgvRoadWay = new HikAgvRoadWayJL();
        hikAgvRoadWay.setRoadWayCode(roadWayCode);
        hikAgvRoadWay.setSeq("0");
        hikAgvRoadWayJLMapper.updateById(hikAgvRoadWay);
        return ResponseData.success();
    }
    @Override
    public void agvCallback(HiKAgvCallbackParm hiKAgvCallbackParm) {
        //时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 获取taskCode，
        String taskCode = hiKAgvCallbackParm.getTaskCode();
        // 获取 操纵方法
        String method = hiKAgvCallbackParm.getMethod();
        // 获取AGV小车
        String robotCode = hiKAgvCallbackParm.getRobotCode();
        // 巷道编号
        String roadWayCode = hiKAgvCallbackParm.getRoadWayCode();
        // 巷道内顺序号
        String seq = hiKAgvCallbackParm.getSeq();

        // 当前位置编号
        String currentPositionCode = hiKAgvCallbackParm.getCurrentPositionCode();
        HikAgvTaskJLParam paramCondition = new HikAgvTaskJLParam();
        paramCondition.setTaskNo(taskCode);
        if ("outbin".equals(method)) {
            // 离开存储位，将任务状态修改为 10
            paramCondition.setAgvCode(robotCode);
            paramCondition.setStat("10");
            paramCondition.setGetCompleteTime(new Date());
            this.baseMapper.updateByTaskNo(paramCondition);
        } else if ("end".equals(method)) {
            // 任务结束，将任务状态修改为 20
            paramCondition.setStat("20");
            paramCondition.setPutCompleteTime(new Date());
            this.baseMapper.updateByTaskNo(paramCondition);
            if (StringUtils.isNotBlank(roadWayCode) && StringUtils.isNotBlank(seq)) {
                HikAgvRoadWayJL hikAgvRoadWayJL = new HikAgvRoadWayJL();
                hikAgvRoadWayJL.setRoadWayCode(roadWayCode);
                hikAgvRoadWayJL.setSeq(seq);
                hikAgvRoadWayJLMapper.updateById(hikAgvRoadWayJL);
            }
        } else if ("cancel".equals(method)) {
            // 任务取消，将任务状态修改为 90
            paramCondition.setStat("90");
            paramCondition.setCancelTime(new Date());
            this.baseMapper.updateByTaskNo(paramCondition);
        }

    }
    @Override
    public ResponseData setPriority(HikAgvTaskJLParam param) {
        User user = userAop.getUser();
        BasicCustomer r = basicCustomerService.lambdaQuery().eq(BasicCustomer::getDeptId, user.getDeptId()).one();

        HikRsVo hikRsVo = HikApiUtils.setTaskPriorityJL(r.getAgvBaseUrl(), param);
        if (hikRsVo == null) {
            return ResponseData.error("接口调用错误");
        } else if (!"0".equals(hikRsVo.getCode() )) {
            return ResponseData.error(hikRsVo.getMessage());
        }
        HikAgvTaskJLParam save = new HikAgvTaskJLParam();
        save.setId(param.getId());
        save.setPriority(param.getPriority());

        HikAgvTaskJL oldEntity = getOldEntity(save);
        HikAgvTaskJL newEntity = getEntity(save);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
        return ResponseData.success();


    }
    @Override
    public ResponseData cancelTask(String taskCode) {
        User user = userAop.getUser();
        BasicCustomer r = basicCustomerService.lambdaQuery().eq(BasicCustomer::getDeptId, user.getDeptId()).one();

        HikRsVo hikRsVo = HikApiUtils.cancelTask(r.getAgvBaseUrl(), taskCode);
        if (hikRsVo == null) {
            return ResponseData.error("接口调用错误");
        } else if (!"0".equals(hikRsVo.getCode() )) {
            return ResponseData.error(hikRsVo.getMessage());
        }

        return ResponseData.success();
    }
}
